﻿namespace Deppton.Mobile.Services
{
    using Deppton.Mobile;
    using Deppton.Model;
    using System.IO;
    using System.Collections.Generic;

    public class SurveysStorageService : ISurveysStorageService
    {
        private static string SurveysStoragePath
        {
            get
            {
                // It is much more comfortable when testing surveys and its definition to share
                // a folder in your hard drive with the mobile device emulator and edit the
                // files from the host machine.
                // If you want to do so uncomment the following line.
                // Remember that there is a similar one in the SurveyDefinitionsStorageService class.
                //// return Path.Combine(PathUtilities.GetStorageCardPath(), "surveys");

                return Path.Combine(PathUtilities.GetExecutionPath(), "surveys");
            }
        }

        public void Store(Survey survey)
        {
            FilesystemHelpers.SurveyFilesystemHandler.SaveToFile(survey, GetSurveyFilePath(survey.Id));
        }

        public Survey[] RetrieveAll()
        {
            var surveys = new List<Survey>();

            foreach (var file in Directory.GetFiles(SurveysStoragePath, "*.xml"))
            {
                surveys.Add(FilesystemHelpers.SurveyFilesystemHandler.LoadFromFile(Path.Combine(SurveysStoragePath, file)));
            }

            return surveys.ToArray();
        }

        public Survey Retrieve(string surveyId)
        {
            var file = GetSurveyFilePath(surveyId);

            if (!File.Exists(file))
            {
                return null;
            }
            else
            {
                return FilesystemHelpers.SurveyFilesystemHandler.LoadFromFile(file);
            }
        }

        private string GetSurveyFilePath(string surveyId)
        {
            return Path.Combine(SurveysStoragePath, Path.Combine(SurveysStoragePath, string.Format("{0}.xml", surveyId)));
        }

        public void Delete(string surveyId)
        {
            var file = GetSurveyFilePath(surveyId);

            if (File.Exists(file))
            {
                File.Delete(file);
            }
        }
    }
}
